package com.sp.scmdb.jobImpl;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;

import com.sp.scmdb.entity.Employee;
import com.sp.scmdb.entity.His_Original;
import com.sp.scmdb.entity.LabelReadingMachine;
import com.sp.scmdb.job.DealWithReaderJob;
import com.sp.scmdb.service.ParseDataService;
import com.sp.scmdb.service.ViolationRecordService;

public class DealWithReaderJobImpl implements DealWithReaderJob {

	private static Log log = LogFactory.getLog(DealWithReaderJobImpl.class);
	
	private ParseDataService parseDataService;
	private ViolationRecordService violationRecordService;

	@Autowired
	public void setParseDataService(ParseDataService parseDataService) {
		this.parseDataService = parseDataService;
	}
	
	@Autowired
	public void setViolationRecordService(ViolationRecordService violationRecordService) {
		this.violationRecordService = violationRecordService;
	}

	public void doParticipateSecurity() {
		delTodayBeforeOldOriginal();
		parseOriginal();
		parseSecurityTraining();
//		parseOriginalDangerSource();
//		sendReaderDangerousSMS();
		
		readerAlarm();
	}

	@SuppressWarnings("unchecked")
	private void parseOriginal()
	{
		try
		{
			DateTimeFormatter formatter =DateTimeFormat.forPattern("yyyy-MM-dd");
			DateTime now = formatter.parseDateTime(new DateTime().toString("yyyy-MM-dd"));
			
			List list = parseDataService.findSql("select CONVERT(varchar(10), nextRemindDate, 23) nextRemindDate, taskType"
					+ " from OBJ_TaskDoDateRecord where taskType = 'securityCommented'");
			DateTime nextRemindDate = now;
			if(CollectionUtils.isNotEmpty(list))
			{
				HashMap map = (HashMap)list.get(0);
				nextRemindDate = formatter.parseDateTime(map.get("nextRemindDate").toString());
				
				if(now.isBefore(nextRemindDate)) {
					return;
				}
			}
			
			StringBuffer sqlBuffer = new StringBuffer();
			String readerHql = "from LabelReadingMachine where lrmState = 1 and monitorDaySecurity = 1";
			String empHql = "select new Employee(id, empLableID) from Employee order by id asc";
			List<LabelReadingMachine> readerList = parseDataService.findReader(readerHql);
			if(CollectionUtils.isNotEmpty(readerList))
			{
				for(LabelReadingMachine reader : readerList)
				{
					int lrmID = reader.getLrmID();
					List<Employee> empList = parseDataService.findEmp(empHql);
					if(CollectionUtils.isNotEmpty(empList))
					{
						for(Employee emp : empList)
						{
							String labelID = emp.getEmpLableID();
							List<His_Original> originalList = parseDataService.findHisOriginal
							("from His_Original where lrmID = " + lrmID + " and labelID = " + labelID 
									+ " and CONVERT(varchar(10), dataTime, 23) = '" + nextRemindDate.toString("yyyy-MM-dd") + "' "
									+ " order by Data_Time asc");
							if(CollectionUtils.isNotEmpty(originalList))
							{
								long lastMillis = 0;
								int i = 0;
								int values = 0;
								for(His_Original original : originalList)
								{
									long currentMillis = original.getDataTime().getMillis();
									if(i != 0)
									{
										//如果两个时间相差大于30秒就不算是连续存在
										if((currentMillis - lastMillis) / 1000 > 30)
										{
											values = 0;
										} else {
											values += (currentMillis - lastMillis) / 1000;
										}
									}
									
									lastMillis = currentMillis;
									i = 1;
									
									if(values >= 60) break;
								}
								
								if(values >= 60) 
								{   //大于等于3分钟则参见安全讲评, 不论哪个监控每日安全讲评的读到, 都记为读到, 不需要重复添加
									sqlBuffer.append(" if not exists (select * from Security_ParticipateCommented")
											 .append(" where labelId = " + emp.getEmpLableID() + " and participateDate = '" + nextRemindDate.toString("yyyy-MM-dd") + "')");
									sqlBuffer.append("insert into Security_ParticipateCommented values(" + emp.getId() + ",")
											 .append(" " + emp.getEmpLableID() + ", ")
											 .append(" " + reader.getId() + ", ")
											 .append(" " + reader.getLrmID() + ", ")
											 .append(" '" + nextRemindDate.toString("yyyy-MM-dd") + "');" );
									//如果当前nextRemind日期和strNow现在系统日期相等, 更新OBJ_EMPLOYEE表safetys = 1, 当天参加安全讲评
								}
							}
						}
					}
				}
			}
			
			if(nextRemindDate.equals(now))
			{
				//更新任务执行时间
			}
			else
			{
			sqlBuffer.append(" delete from OBJ_TaskDoDateRecord where taskType = 'securityCommented';")
					 .append(" insert into OBJ_TaskDoDateRecord")
					 .append(" values('" + nextRemindDate.plusDays(1).toString("yyyy-MM-dd") + "'")
					 .append(" ,'securityCommented')");
			}
			
			sqlBuffer.append(" update OBJ_EMPLOYEE set safetys = 2;");
			sqlBuffer.append(" update OBJ_EMPLOYEE set safetys = 1 where id = ");
			sqlBuffer.append(" (select empId from Security_ParticipateCommented p where p.empId = OBJ_EMPLOYEE.id and '" + nextRemindDate.toString("yyyy-MM-dd") + "' = p.participateDate)");
			
			if(StringUtils.isNotEmpty(sqlBuffer.toString()))
			{
				parseDataService.execute(sqlBuffer.toString());
			}
			
			//sql查询
//			String sql = "select original.* from OBJ_OLDORIGINAL original";
//			sql += " inner join OBJ_READERS reader on reader.lrmID = original.lrmID";
//			sql += " inner join OBJ_EMPLOYEE employee on employee.empLabelID = original.labelID";
//			sql += " where CONVERT(varchar(10), Data_Time, 23) = '" + strNow + "'";
//			sql += " and reader.lrmState = 1 and reader.monitorDaySecurity = 1";
//			sql += " and employee.empWorkTypeID between 29 and 39";
//			sql += " order by original.Data_Time asc";
//			List originalList = parseDataService.findSql(sql);
//			if(CollectionUtils.isNotEmpty(originalList)) {
//				originalList = ConvertMapToBean.convertMap(originalList, OriginalBean.class);
//				for(Object object : originalList) {
//					OriginalBean original = (OriginalBean) object;
//					log.info("**************************" + original.getData_Time().toString("yyyy-MM-dd HH:mm:s"));
//				}
//			}
		} 
		catch (Exception e) 
		{
			log.error("operator parseOriginal error:" + e.getMessage());
		}
	}
	@SuppressWarnings("unchecked")
	private void parseSecurityTraining()
	{
		DateTimeFormatter formatter =DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
		DateTime now = formatter.parseDateTime(new DateTime().toString("yyyy-MM-dd HH:mm:ss"));
		String strNow = now.minusMinutes(10).toString("yyyy-MM-dd HH:mm:ss"); //往前推迟10分钟, 最近10分钟
		
		List list = parseDataService.findSql("select nextRemindDate from OBJ_TaskDoDateRecord "
				+ " where taskType = 'securityTraining'");
		DateTime nextRemindDate = now;
		boolean exec = false;
		if(CollectionUtils.isNotEmpty(list))
		{
			HashMap map = (HashMap)list.get(0);
			nextRemindDate = formatter.parseDateTime(map.get("nextRemindDate").toString());
			if(now.isBefore(nextRemindDate))
			{
				exec = true;
				return;
			}
		}
		String readerHql = "from LabelReadingMachine where lrmState = 1 and securityTrainingId is not null";
		//String empHql = "select new Employee(id, empLableID) from Employee where empType = 2 order by id asc";
		String empSql = "select distinct employee.id, employee.empLabelID from OBJ_OLDORIGINAL original";
		empSql += " inner join OBJ_EMPLOYEE employee on original.labelID = employee.empLabelID";
		empSql += " where CONVERT(varchar(20), original.Data_Time, 20) >= '" + strNow + "'";
		empSql += " and employee.empType = 2";

		List<LabelReadingMachine> readerList = parseDataService.findReader(readerHql);
		if(CollectionUtils.isNotEmpty(readerList))
		{
			for(LabelReadingMachine reader : readerList)
			{
				if(exec) break;
				int lrmID = reader.getLrmID();
				List empList = parseDataService.findSql(empSql);
				if(CollectionUtils.isNotEmpty(empList))
				{
					for(Object emp : empList)
					{
						if(exec) break;
						HashMap map = (HashMap)emp;
						String labelID = map.get("empLabelID").toString();
						List<His_Original> originalList = parseDataService.findHisOriginal
						("from His_Original where lrmID = " + lrmID + " and labelID = " + labelID 
								+ " and CONVERT(varchar(20), dataTime, 20) > '" + strNow + "' "
								+ " order by Data_Time asc");
						if(CollectionUtils.isNotEmpty(originalList))
						{
							long lastMillis = 0;
							int i = 0;
							int values = 0;
							for(His_Original original : originalList)
							{
								if(exec) break;
								long currentMillis = original.getDataTime().getMillis();
								if(i != 0)
								{
									if((currentMillis - lastMillis) / 1000 > 30) 
									{
										values = 0;
									} else {
										values += (currentMillis - lastMillis) / 1000;
									}
								}
								lastMillis = currentMillis;
								i = 1;
								if(values >= 180) break;
							}
							if(values >= 180) //如果停留时间大于3分钟
							{
								String empId = map.get("id").toString(); //查看是否参加过安全培训交底
								
								if(reader.getSecurityTraining() == null) break;
								String manIds = reader.getSecurityTraining().getTrainMans() + ",";
								if(!manIds.contains(empId + ","))
								{
									try {
										//发送到项目副经理
										alarmSMS("13636437769", "读头:" + lrmID + ", 发现卡号：" + labelID + "没有参加过安全培训交底!");
									} catch (Exception e) {
									}
								}
							}
						}
					}
				}
			}
		}
		
		if(CollectionUtils.isNotEmpty(list))
		{
			DateTime nextAlarmTime = now.plusHours(2); //间隔2小时执行
			parseDataService.execute("update OBJ_TaskDoDateRecord set nextRemindDate = '" + nextAlarmTime.toString("yyyy-MM-dd HH:mm:ss") + "' where taskType = 'securityTraining' ");
		}
		else
		{
			DateTime nextAlarmTime = now.plusHours(2); //间隔2小时执行
			parseDataService.execute("insert into OBJ_TaskDoDateRecord values('" + nextAlarmTime.toString("yyyy-MM-dd HH:mm:ss") + "', 'securityTraining')");
		}
	}
	
	@SuppressWarnings("unchecked")
	private void parseOriginalDangerSource() {
		List<LabelReadingMachine> readerList = parseDataService
			.findReader("from LabelReadingMachine where dangerousMans is not null and dangerousMans <> '' ");
		for(LabelReadingMachine reader : readerList) {
			String sql = "select distinct employee.id from OBJ_OLDORIGINAL origninal, OBJ_EMPLOYEE employee";
			sql += " where CONVERT(varchar(20), Data_Time, 23) = '" + new DateTime().toString("yyyy-MM-dd") + "'";
			sql += " and lrmID = " + reader.getLrmID();
			sql += " and origninal.labelID = employee.empLabelID";
			List empList = parseDataService.findSql(sql);
			int cnt = 0;
			for(Object obj : empList) {
				HashMap map = (HashMap)obj;
				String[] mainIds = reader.getDangerousMans().split(",");
				String empId = map.get("id").toString();
				for(int i = 0; i < mainIds.length; i++) {
					if(mainIds[i].equals(empId)) {
						cnt = 1;
						break;
					}
				}
				if(cnt == 1) break;
			}
			if(empList.size() > 0 && cnt == 0) { //说明该读头下未发现危险源监管人员, 短信报警
				float hours = reader.getOftenHoursSendSMS();
				int minutes = (int) (hours * 60);
				DateTime alarm = new DateTime().plusMinutes(minutes);
				
				String smsSql = "if not exists (select * from OBJ_ReaderDangerous where lrmID = " 
					+ reader.getLrmID() + " and CONVERT(varchar(10), alarmDate, 23) = '" + new DateTime().toString("yyyy-MM-dd")  + "')";
				smsSql += "insert into OBJ_ReaderDangerous values(" + reader.getLrmID() + ", '" + alarm.toString("yyyy-MM-dd HH:mm:ss") + "', null, 1)";
				parseDataService.execute(smsSql);
			}
		}
	}
	
	private static final String projectId = "40288015215f25800121636c6f310428";
	private void sendReaderDangerousSMS() {
		String readerDangerousSql = "select dangerous.id, dangerous.lrmID, CONVERT(varchar(50), dangerous.alarmDate, 20) alarmDate, confirmDate, level, reader.RMK"
			+ " from OBJ_ReaderDangerous dangerous, OBJ_READERS reader where confirmDate is null and dangerous.lrmID = reader.lrmID";
		List list =  parseDataService.findSql(readerDangerousSql);
		for(Object ob : list) {
			HashMap mp = (HashMap)ob;
			String strAlarmDate = mp.get("alarmDate").toString();
			DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
			DateTime alarmDate = formatter.parseDateTime(strAlarmDate);
			if(alarmDate.isBefore(new DateTime())) {
				//查看是否危险源监管人员是否已经到场
				String sql = "select distinct employee.id, origninal.lrmID, reader.dangerousMans ";
				sql += " from OBJ_OLDORIGINAL origninal, OBJ_EMPLOYEE employee, OBJ_READERS reader";
				sql += " where CONVERT(varchar(20), Data_Time, 23) = '" + new DateTime().toString("yyyy-MM-dd") + "'";
				sql += " and origninal.lrmID = " + mp.get("lrmID").toString();
				sql += " and origninal.labelID = employee.empLabelID";
				sql += " and origninal.lrmID = reader.lrmID";
				List empList = parseDataService.findSql(sql);
				int cnt = 0;
				for(Object obj : empList) {
					HashMap map = (HashMap)obj;
					String[] mainIds = map.get("dangerousMans").toString().split(",");
					String empId = map.get("id").toString();
					for(int i = 0; i < mainIds.length; i++) {
						if(mainIds[i].equals(empId)) {
							cnt = 1;
							break;
						}
					}
					if(cnt == 1) break;
				}
				
				String level = mp.get("level").toString();
				String nextLevel = "5";
				DateTime now = new DateTime();
				if(empList.size() > 0 && cnt == 0) {
					//说明未到场, 发送短信
					if(level.equals("1")) 
						{ alarmSMS2(projectId, "安全部#安全员", "上海轨道交通12号线土建工程11标段,危险源监管人员未到场,危险源性质:" + mp.get("RMK").toString()); nextLevel = "2"; now = now.plusMinutes(5); }
						//{ alarmSMS("13636437769", "上海轨道交通12号线土建工程11标段,危险源监管人员未到场,危险源性质:" + mp.get("RMK").toString()); }
					else if(level.equals("2")) 
						{ alarmSMS2(projectId, "项目办公室#项目副经理", "上海轨道交通12号线土建工程11标段,危险源监管人员未到场,危险源性质:" + mp.get("RMK").toString()); nextLevel = "3"; now = now.plusMinutes(10); } 
						//{ alarmSMS("13636437769", "上海轨道交通12号线土建工程11标段,危险源监管人员未到场,危险源性质:" + mp.get("RMK").toString()); }
					else if(level.equals("3"))
						{ alarmSMS2(projectId, "项目办公室#项目经理", "上海轨道交通12号线土建工程11标段,危险源监管人员未到场,危险源性质:" + mp.get("RMK").toString()); nextLevel = "4"; now = now.plusMinutes(15); }
						//{ alarmSMS("13636437769", "上海轨道交通12号线土建工程11标段,危险源监管人员未到场,危险源性质:" + mp.get("RMK").toString()); }
					else if(level.equals("4")) { alarmSMS("13311653375", "上海轨道交通12号线土建工程11标段,危险源监管人员未到场,危险源性质:" + mp.get("RMK").toString()); nextLevel = "5"; now = now.plusMinutes(20); }
					else if(level.equals("5")) { alarmSMS("13817699590", "上海轨道交通12号线土建工程11标段,危险源监管人员未到场,危险源性质:" + mp.get("RMK").toString()); }
				}
				
				String updSql = "update OBJ_ReaderDangerous set confirmDate = '" + new DateTime().toString("yyyy-MM-dd HH:mm:ss") + "' where id = " + mp.get("id").toString();
				if(!level.equals("5")) updSql += " insert into OBJ_ReaderDangerous values(" + mp.get("lrmID").toString() + ", '" + now.toString("yyyy-MM-dd HH:mm:ss") + "', null, " + nextLevel + ")";
				parseDataService.execute(updSql);
			}
		}
	}
	
	private void alarmSMS(String mobile, String msg) {
		try {
			String url = "http://gms.sucgm.com:8081/chengjian/webservices/SendSMSWebService.asmx?wsdl";
			String namespace = "http://gms.sucgm.com/";
			String methodName = "sendSMS";
			String soapActionURI = "http://gms.sucgm.com/sendSMS";
			msg = URLEncoder.encode(msg, "utf-8");
			
			Service service = new Service();
			Call call = null;
			call = (Call) service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(url));
			call.setSOAPActionURI(soapActionURI);
			call.setOperationName(new QName(namespace, methodName));
			
			call.addParameter(new QName(namespace, "uName"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter(new QName(namespace, "uPwd"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter(new QName(namespace, "mobile"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter(new QName(namespace, "msg"), XMLType.XSD_STRING, ParameterMode.IN);
			call.setReturnType(XMLType.XSD_STRING);

			String str = (String) call.invoke(new Object[] { "sucgm", "sucgm2013", mobile, msg });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void delTodayBeforeOldOriginal() {
		//删除不是当天的数据
		String strDate = new DateTime().toString("yyyy-MM-dd");
		String sql = "delete from OBJ_OLDORIGINAL where Data_Time < '" + strDate  + "' ";
		parseDataService.execute(sql);
	}
	
	private void alarmSMS2(String projectId, String deptpostName, String msg) {
		try {
			String url = "http://gms.sucgm.com:8081/chengjian/webservices/SendSMSWebService.asmx?wsdl";
			String namespace = "http://gms.sucgm.com/";
			String methodName = "sendSMS2";
			String soapActionURI = "http://gms.sucgm.com/sendSMS2";
			msg = URLEncoder.encode(msg, "utf-8");
			
			Service service = new Service();
			Call call = null;
			call = (Call) service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(url));
			call.setSOAPActionURI(soapActionURI);
			call.setOperationName(new QName(namespace, methodName));
			
			call.addParameter(new QName(namespace, "uName"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter(new QName(namespace, "uPwd"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter(new QName(namespace, "projectId"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter(new QName(namespace, "deptpostName"), XMLType.XSD_STRING, ParameterMode.IN);
			call.addParameter(new QName(namespace, "msg"), XMLType.XSD_STRING, ParameterMode.IN);
			call.setReturnType(XMLType.XSD_STRING);

			String str = (String) call.invoke(new Object[] { "sucgm", "sucgm2013", projectId, deptpostName, msg });
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void readerAlarm() {
//		String readerHql = "from LabelReadingMachine ";
//		if(CollectionUtils.isNotEmpty(readerList))
//		{
//			for(LabelReadingMachine reader : readerList)
//			{
//				int lrmID = reader.getLrmID();
//			}
//		}
	}
	
	public static void main(String[] args) {
		//15601789080
		DealWithReaderJobImpl main = new DealWithReaderJobImpl();
		//main.alarmSMS("13636437769", "ceshi测试, 公司明天组织去欢乐谷!");
	}
}
